package com.example.wxai.service.impl;


import com.example.wxai.mapper.ChatMapper;
import com.example.wxai.pijo.entity.Chat;
import com.example.wxai.service.IChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wxai.service.IMessageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 大聊天表，记录总聊天 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-28
 */
@Slf4j
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements IChatService {

    @Resource
    private IMessageService messageService;
    @Override
    @Transactional
    public boolean saveAndMessage(String userId, List<Message> message, String chatId) {
        log.info("存入数据库{}",chatId);
        Chat one = lambdaQuery().eq(Chat::getChatId, chatId).one();
        if (Objects.nonNull(one)){
            one.setUpdateTime(LocalDateTime.now());
            updateById(one);
        }else {
            Chat chat=new Chat();
            chat.setChatId(chatId);
            chat.setUserId(userId);
            chat.setCreatTime(LocalDateTime.now());
            chat.setUpdateTime(LocalDateTime.now());
            chat.setIdDelete(false);
            chat.setTitle(message.get(0).getText());
            log.info("存入数据库{}",chat);
            boolean save = save(chat);
            log.info("存入数据库{}",save);
        }

        message.forEach(e->{
            com.example.wxai.pijo.entity.Message message1=new com.example.wxai.pijo.entity.Message();
            message1.setMessageType(e.getMessageType().toString());
            message1.setMessage(e.getText());
            message1.setChatId(chatId);
            message1.setIsDelete(false);
            message1.setCreatTime(LocalDateTime.now());
            messageService.save(message1);
        });
        return true;
    }
}
